<template>
  <div style="display: flex">
    <category-panel title="分类" icon="tree" request="memberCategory" @delClick="delClick" @notClick="notClick" @nodeClick="nodeClick" /><el-container>
      <el-header>
        <div class="report_header" ref="headerHeight">
          <div class="report_header_left"></div>
          <div style="width: 300px;display: flex;align-items: center;margin-left: 10px;">
            <svg-icon class="primary" :icon-class="$route.meta.icon"/>
            <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
            <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px">

              <div class="report_header_query">
                <el-input v-model="query.name" prefix-icon="el-icon-search" placeholder="输入客户信息" />
              </div>
              <div class="report_header_query">
                <el-select v-model="query.vipId" clearable placeholder="请选择状态">
                  <el-option
                    v-for="item in vipList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </div>
            </div>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryClick">查询</el-button>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
                       v-permission="['member.add']">新增</el-button>
            <el-button @click="handleDownload" v-permission="['member.export']"  style="margin-left: 10px;margin-top: 5px;" size="mini" type="info" icon="el-icon-plus">导入导出</el-button>
          </div>
        </div>
<!--        <div>-->
<!--          <svg-icon class="primary" :icon-class="$route.meta.icon" />-->
<!--          <span class="primary">{{ $route.meta.title }}</span>-->
<!--        </div>-->
<!--        <div class="header-button-container">-->
<!--          <el-button :icon="queryType? 'el-icon-search':'el-icon-close'" type="primary" @click="chooseClick">{{ queryType == false?'隐藏':'查询' }}</el-button>-->
<!--          <el-button v-permission="['member.add']" icon="el-icon-plus" type="info" style="margin-left: 10px" @click="addClick">新增</el-button>-->
<!--          <el-button @click="handleDownload" v-permission="['member.export']" type="info" icon="el-icon-plus">导入导出</el-button>-->
<!--        </div>-->
      </el-header>
      <div class="pd10">
<!--        <div v-show="queryType == false" style="margin-bottom: 10px;display: flex;align-items: center">-->
<!--          <el-input v-model="query.name" prefix-icon="el-icon-search" placeholder="客户名称" style="width: 200px"/>-->
<!--          <el-input v-model="query.address" prefix-icon="el-icon-search" placeholder="客户地址" style="width: 200px;margin-left: 10px"/>-->
<!--          <el-input v-model="query.phone" prefix-icon="el-icon-search" placeholder="联系电话" style="width: 200px;margin-left: 10px"/>-->
<!--          <el-select v-model="query.vipId" placeholder="请选择状态" style="margin-left: 10px">-->
<!--            <el-option-->
<!--              v-for="item in vipList"-->
<!--              :key="item.id"-->
<!--              :label="item.name"-->
<!--              :value="item.id"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--          <el-button style="margin-left: 10px" icon="el-icon-search" type="primary" @click="queryClick">查询</el-button>-->
<!--          <el-button style="margin-left: 10px" icon="el-icon-refresh-right" type="info" @click="resetClick">重置</el-button>-->
<!--        </div>-->
        <el-table ref="table" v-loadMore="[payLoads,'member-list']" @sort-change="sortChange" :data="memberData" border stripe :height="curHeight" style="width: 100%;">
          <el-table-column type="index" width="50" align="center" fixed />
          <el-table-column sortable label="客户名称" width="180" align="center" prop="name" />
          <el-table-column sortable label="注册时间" width="120" align="center" prop="createDate">
            <template slot-scope="scope">
              <span>{{ scope.row.createDate| dateFormatter }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="等级" width="80" align="center" prop="vip">
            <template slot-scope="scope">
              <span>{{ scope.row.vipName }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="注册手机" width="180" align="center" prop="mobile" />
          <el-table-column label="会员编码" width="100" align="center" prop="code" />
          <el-table-column label="所属门店" width="130" align="center" prop="shopName" />
          <el-table-column label="金币" width="120" align="right" prop="point"></el-table-column>
          <el-table-column sortable label="消费金额" width="120" prop="amount" align="right">
            <template slot-scope="scope">
              <span>{{ Number(scope.row.amount).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="绩效金额" width="120" align="right" prop="achieve"></el-table-column>
          <el-table-column label="性别" width="60" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.gender | watchGender }}</span>
            </template>
          </el-table-column>
          <el-table-column label="地址" width="360" align="center" >
            <template slot-scope="scope">
              <span >{{ scope.row.areaName }}{{ scope.row.address }}</span>
            </template>
          </el-table-column>

          <el-table-column label="备用电话" width="180" align="center" prop="phone" />
          <el-table-column label="邮箱" width="150" align="center" prop="email" />
          <el-table-column label="会员有效期" width="150" align="center" >
            <template slot-scope="scope">{{ scope.row.vipExpired | dateFormatter }}</template>
          </el-table-column>

          <el-table-column label="功能" align="center" prop="remark" width="80" fixed="right">
            <template slot-scope="scope">
              <el-tooltip v-show="deleted == false" v-permission="['member.edit']" class="item" effect="dark" content="详情" placement="top-start">
                <el-button type="primary" size="mini" @click="detailClick(scope.row)">详情</el-button>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" fixed="right" width="80">
            <template slot-scope="scope">
              <div>
                <el-tooltip v-show="deleted == false" v-permission="['member.edit']" class="item" effect="dark" content="编辑" placement="top-start">
                  <a @click="editClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-edit" />
                  </a>
                </el-tooltip>
                <el-tooltip v-show="deleted == false" v-permission="['member.del']" class="item" effect="dark" content="删除" placement="top-start">
                  <a style="margin-left: 10px" @click="deleteMember(scope.row)">
                    <i style="color: #F56C6C" class="el-icon-delete" />
                  </a>
                </el-tooltip>
                <el-tooltip v-show="deleted == true" v-permission="['member.del']" class="item" effect="dark" content="恢复客户" placement="top-start">
                  <a style="margin-left: 10px" @click="restoreMember(scope.row)">
                    <i style="color: #E6A23C" class="el-icon-refresh-right" />
                  </a>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadMember" />
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import { list, del, updateMember } from '@/api/member'
import utils from '../../utils/utils.js'
import { EventBus } from '@/api/eventBus'
import Pagination from '@/components/Pagination'
import CategoryPanel from '@/components/CategoryPanel'
import loadMore from '@/utils/loadMore.js'
import {list as vipList} from "../../api/vip";
export default {
  name: 'member-list',
  directives: { permission, loadMore },
  components: { Pagination, CategoryPanel },
  filters: {
    formatDate: function(value) {
      const date = new Date(value)
      const y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? ('0' + MM) : MM
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      return y + '-' + MM + '-' + d
    },
    watchGender(val) {
      if (val == 0) {
        return '男'
      } else if (val == 1) {
        return '女'
      } else {
        return '隐藏'
      }
    },
    watchVip(val) {
      if (val == 0) {
        return 'vip0'
      } else if (val == 1) {
        return 'vip1'
      } else if (val == 2) {
        return 'vip2'
      } else if (val == 3) {
        return 'vip3'
      } else if (val == 4) {
        return 'vip4'
      } else if (val == 5) {
        return 'vip5'
      }
    }
  },
  data() {
    return {
      memberData: [],
      pageNum: 1,
      pageSize: 20,
      total: 0,
      queryType: true,
      payLoads: '',
      query: {
        name: '',
        phone: '',
        vipId:'',
        address:''
      },
      keyword: {
        name: '',
        phone: '',
        vipId:'',
        address:''
      },
      queryPhone: '',
      queryName: '',
      curHeight: null,
      excelData: [],
      memberCategoryId: '',
      deleted: false,
      sortField: "", // 排序
      direction: '',
      restoreForm: {
        id: '',
        deleted: false
      },
      vipList:[],
    }
  },
  created() {
    var _this = this
    this.loadMember()
    this.loadVip()
    EventBus.$on('member-add', res => { // 监听新增完毕
      // 更新列表数组
      _this.memberData.splice(0, 0, res)
    })
    EventBus.$on('member-edit', res => { // 监听新增完毕
      // 更新列表数组
      for (var i = 0; i < _this.memberData.length; i++) {
        if (_this.memberData[i].id == res.id) {
          _this.memberData[i] = res
        }
      }
    })
  },
  mounted() {
    this.comeIn()
    this.beforeMount()
  },
  activated() {
    this.payLoads = new Date().getTime()
  },
  methods: {

    beforeMount() {
      window.onresize = () => {
        return (() => {
          if (this.queryType == false) {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            this.curHeight = h - 266// 减去页面上固定高度height
          } else {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            this.curHeight = h - 220// 减去页面上固定高度height
          }
        })()
      }
    },
    comeIn() {
      console.log('222')
      var h = document.documentElement.clientHeight || document.body.clientHeight
      this.curHeight = h - 220// 减去页面上固定高度height
    },
    editClick(row) {
      this.$router.push({
        path: '/member/edit', query: { id: row.id }
      })
    },
    loadMember(val) {
      console.log(val)
      var _this = this
      const params = new URLSearchParams()
      params.append('pageNum', _this.pageNum)
      params.append('pageSize', _this.pageSize)
      params.append('phone', _this.keyword.phone)
      params.append('address',_this.keyword.address)
      params.append('keyword', _this.keyword.name)
      params.append('vipId', _this.keyword.vipId)
      params.append('memberCategoryId', _this.memberCategoryId)
      params.append('deleted', _this.deleted)
      params.append('sortField', _this.sortField)
      params.append('direction', this.direction)
      list(params).then(response => {
        _this.memberData = response.data.data
        _this.total = response.data.total
      }).catch(error => {
        console.log('error!!')
      })
    },

    chooseClick() {
      this.queryType = !this.queryType
      if (this.queryType == false) {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 266// 减去页面上固定高度height
      } else {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220// 减去页面上固定高度height
      }
    },
    addClick() {
      this.$router.push({
        path: '/member/add'
      })
    },
    deleteMember(data) {
      console.log(data)
      var _this = this
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(data.id).then(response => {
          console.log(response)
          _this.memberData.forEach(function(item, index) {
            if (item.id == data.id) {
              _this.memberData.splice(index, 1)
            }
          })
          _this.$message({
            message: `删除客户${response.content}`,
            offset: 120,
            center: true
          })
        }).catch(error => {
          console.log('error!!')
        })
      }).catch(() => {
      })
    },
    restoreMember(row) {
      console.log(row)
      this.$confirm('确认恢复?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateMember({ id: row.id, deleted: false }).then(() => {
          // 更新列表数组
          this.memberData.forEach((item, index) => {
            if (item.id == row.id) {
              this.memberData.splice(index, 1)
              this.$message({ message: '已成功恢复', type: 'success' })
            }
          })
        }).catch(() => {})
      }).catch(() => {})
    },
    queryClick() {
      this.keyword = this.query
      this.pageNum = 1
      this.loadMember()
    },
    resetClick() {
      this.query.phone = ''
      this.query.name = ''
      this.query.vipId=''
      this.query.address = ''
      this.keyword = this.query
      this.pageNum = 1
      this.loadMember()
    },
    handleDownload() {
      this.$router.push({
        path: "/member/memberExport"
      })
    },
    /* handleDownload() {
      this.prepareExcel()
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['序号', '姓名', '电话', '备用电话', '地址', '邮箱', '性别', '生日', '等级', '可用余额', '冻结余额', '金币积分']
          const filterVal = ['index', 'name', 'mobile', 'phone', 'areaName', 'email', 'gender', 'birth', 'vip', 'balance', 'freezeBalance', 'point']
          const list = this.excelData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
    }, */
    prepareExcel() {
      var _this = this
      const params = new URLSearchParams()
      params.append('pageNum', 1)
      params.append('pageSize', 10000)
      params.append('phone', _this.keyword.phone)
      params.append('address',_this.keyword.address)
      params.append('keyword', _this.keyword.name)
      params.append('memberCategoryId', _this.memberCategoryId)
      params.append('deleted', _this.deleted)
      list(params).then(response => {
        let ex = {}
        for (var i = 0; i < response.data.data.length; i++) {
          ex = {
            index: i,
            name: response.data.data[i].name,
            mobile: response.data.data[i].mobile,
            phone: response.data.data[i].phone,
            areaName: response.data.data[i].areaName + response.data.data[i].address,
            email: response.data.data[i].email,
            gender: response.data.data[i].gender,
            birth: response.data.data[i].birth,
            vip: response.data.data[i].vip,
            balance: response.data.data[i].balance,
            freezeBalance: response.data.data[i].freezeBalance,
            point: response.data.data[i].point
          }
          _this.excelData.push(ex)
        }
      }).catch(error => {
        console.log('error!!')
      })
    },
    sortChange(column) {
      console.log(column);
      this.sortField = column.prop;
      if (column.order == "ascending") {
        this.direction = "asc";
      } else {
        this.direction = "desc";
      }
      this.loadMember()
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    notClick() {
      this.memberCategoryId = 0
      this.deleted = false
      this.loadMember()
    },
    delClick() {
      this.deleted = true
      this.memberCategoryId = ''
      this.loadMember()
    },
    nodeClick(data) {
      this.deleted = false
      this.memberCategoryId = data.id
      this.loadMember()
    },
    detailClick(row) {
      this.$router.push({
        path: '/member/detail', query: { id: row.id }
        // path:'/receiver/list',query:{memberId:row.id}
      })
    },
    loadVip(){
      let params = new URLSearchParams();
      params.append('pageSize', 2000);
      vipList(params).then(response =>{
        console.log(response)
        this.vipList=response.data.data
      }).catch(error=>{
        console.log('error!!')
      })
    },
  }
}
</script>

<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #f2f2f2;
  }
  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
</style>
